<?php defined('SYSPATH') OR die('No direct access allowed.');

class Permalink_Plugin extends WB_FormItem {
	
	protected $title, $max_length;
	
	public function __construct($name='', $params=array())
	{
		parent::__construct($name, $params);
		
		$this->title = isset($this->params['title']) ? $this->params['title'] : 'title';
		$this->db_columns[$this->title] = $this->db_table.'.'.$this->title;
		
		$this->max_length = isset($this->params['max_length']) ? $this->params['max_length'] : 30;
		$this->max_length = $this->max_length>4 ? $this->max_length : 4;
	}
    
	public function prep_db()
	{
		$value = empty($this->value[$this->name]) ? $this->value[$this->title] : $this->value[$this->name];
			
		$value = utf8::transliterate_to_ascii($value);
		$value = utf8::strip_non_ascii($value);
		$value = strtolower(substr($value, 0, $this->max_length));
		$value = preg_replace('|\s+|', '_', $value);
		
		if ($value!=$value)
		{
			$all_permalinks = $this->collect_permalinks();
			
	        $i = 0;
	        $permalink = $value;
	        while ($strlen = strlen($value))
	        {
	        	while (isset($all_permalinks[$permalink]) && $strlen<$this->max_length)
	        	{
	        		$permalink = $value.$i++;
	        	}
	        	if ( ! isset($all_permalinks[$permalink])) return $permalink;
	        	$value = substr($value, 0, -1);
	        }
		}
		else return $value;
		
		throw new Kohana_Exception('permalink_plugin.outofbounds', $this->get_label());
    }
    
    private function collect_permalinks()
    {
    	$query = Kohana::instance()->db
    				->select($this->form_columns[$this->name].' AS permalink')
    				->from($this->db_table)
    				->get();
    				
    	$similars = array();
    	foreach ($query as $row) $similars[$row->permalink] = $row->permalink;
    	return $similars;
    }
	
}

//End of Permalink_Plugin Library